from moviepy.editor import VideoFileClip, TextClip, CompositeVideoClip
from pathlib import Path
import os
import subprocess


def get_filename(file_path):
    file_name = os.path.splitext(os.path.basename(file_path))[0]
    return file_name


def find_cn_srt(fileName):
    directory = 'buff/4_ctr_wav'
    path = Path(directory)
    for file in path.glob('**/*'):
        if file.is_file() and fileName in file.name:
            return file


def add_subtitles_to_video(input_video, srt_file, output_video):
    # ffmpeg命令
    ffmpeg_cmd = ['ffmpeg', '-i', input_video, '-vf', f'subtitles={srt_file}', output_video]

    try:
        # 运行ffmpeg命令
        subprocess.run(ffmpeg_cmd, check=True)
        print("字幕已成功添加到视频中！")
    except subprocess.CalledProcessError as e:
        print("发生错误，无法添加字幕到视频中。", e)


def convert_time(time_str):
    h, m, s = time_str.split(':')
    s, ms = s.split(',')
    total_seconds = int(h) * 3600 + int(m) * 60 + int(s) + int(ms) / 1000
    return total_seconds


def delete_file(file_path):
    if os.path.exists(file_path):
        os.remove(file_path)
        print(f"文件 {file_path} 已成功删除")
    else:
        print(f"文件 {file_path} 不存在")


def traverse_directory_mp4(directory):
    path = Path(directory)
    for mp4_file in path.glob('**/*.mp4'):
        if mp4_file.is_file():
            # 在这里执行文件操作，例如打印文件路径或进行其他处理
            print(mp4_file)
            mp4_file_name = get_filename(mp4_file)
            cn_srt_file = find_cn_srt(mp4_file_name)
            if cn_srt_file:
                out_file = 'buff/6_mp4_srt/' + mp4_file_name + '.mp4'
                add_subtitles_to_video(mp4_file, cn_srt_file, out_file)
                delete_file(cn_srt_file)
                delete_file(mp4_file)

        if mp4_file.is_dir():
            # 在这里执行子目录操作，例如打印子目录路径或进行其他处理
            print(mp4_file)


path = os.environ['PATH']
os.environ['PATH'] = '/usr/local/bin:' + os.environ['PATH']  # 添加 ffmpeg 路径到环境变量中
os.environ['IMAGEMAGICK_BINARY'] = '/usr/local/bin/convert'  # 添加 ffmpeg 路径到环境变量中
# 指定要遍历的目录路径
mp4_directory_path = 'buff/1_origin_mp4'
# 调用遍历函数
traverse_directory_mp4(mp4_directory_path)
# IMAGEMAGICK_BINARY = '/usr/local/bin/convert'